import React, { useState, useRef, useEffect } from 'react';
import { useNavigate, useLocation } from 'react-router-dom';
import { Globe, ChevronDown, Check } from 'lucide-react';
import { useLanguage } from '../contexts/LanguageContext';
import { US, CN } from 'country-flag-icons/react/3x2';

interface LanguageOption {
  code: 'en' | 'zh-CN';
  name: string;
  nativeName: string;
  FlagComponent: any;
}

const languages: LanguageOption[] = [
  { code: 'en', name: 'English', nativeName: 'English', FlagComponent: US },
  { code: 'zh-CN', name: 'Chinese', nativeName: '简体中文', FlagComponent: CN },
];

const LanguageSwitcher: React.FC = () => {
  const { language, setLanguage } = useLanguage();
  const navigate = useNavigate();
  const location = useLocation();
  const [isOpen, setIsOpen] = useState(false);
  const dropdownRef = useRef<HTMLDivElement>(null);

  const currentLanguage = languages.find(lang => lang.code === language) || languages[0];

  const switchLanguage = (newLanguage: 'en' | 'zh-CN') => {
    if (newLanguage === language) {
      setIsOpen(false);
      return;
    }

    setLanguage(newLanguage);
    setIsOpen(false);

    // Update URL path
    let newPath = location.pathname;
    
    if (newLanguage === 'zh-CN') {
      // Switch to Chinese: add /zh-CN prefix if not present
      if (!newPath.startsWith('/zh-CN')) {
        newPath = `/zh-CN${newPath}`;
      }
    } else {
      // Switch to English: remove /zh-CN prefix if present
      if (newPath.startsWith('/zh-CN')) {
        newPath = newPath.replace(/^\/zh-CN/, '') || '/';
      }
    }

    navigate(newPath);
  };

  // Close dropdown when clicking outside
  useEffect(() => {
    const handleClickOutside = (event: MouseEvent) => {
      if (dropdownRef.current && !dropdownRef.current.contains(event.target as Node)) {
        setIsOpen(false);
      }
    };

    document.addEventListener('mousedown', handleClickOutside);
    return () => document.removeEventListener('mousedown', handleClickOutside);
  }, []);

  return (
    <div className="relative" ref={dropdownRef}>
      <button
        onClick={() => setIsOpen(!isOpen)}
        className="flex items-center gap-2 px-3 py-2 rounded-lg bg-white/10 hover:bg-white/20 transition-all duration-200 text-white border border-white/20 hover:border-white/30 backdrop-blur-sm group"
        aria-label="Select language"
      >
        {/* Globe Icon - Hidden on mobile */}
        <Globe size={16} className="hidden sm:block text-[#00d4ff] transition-transform duration-200" />
        
        {/* Desktop: Flag + Language Name */}
        <div className="hidden sm:flex items-center gap-2">
          <currentLanguage.FlagComponent className="w-6 h-4 rounded shadow-sm" />
          <span className="text-sm font-medium">{currentLanguage.nativeName}</span>
        </div>
        
        {/* Mobile: Flag Only */}
        <div className="sm:hidden flex items-center">
          <currentLanguage.FlagComponent className="w-6 h-4 rounded shadow-sm" />
        </div>
        
        {/* Chevron */}
        <ChevronDown 
          size={14} 
          className={`transition-transform duration-200 ${isOpen ? 'rotate-180' : ''}`} 
        />
      </button>

      {isOpen && (
        <div className="absolute right-0 mt-3 w-52 bg-white/95 dark:bg-gray-800/95 backdrop-blur-xl rounded-2xl shadow-2xl border border-gray-200/50 dark:border-gray-700/50 py-1 z-50 overflow-hidden opacity-0 scale-95 animate-[fadeIn_200ms_ease-out_forwards]">
          <div className="px-4 py-2.5 text-xs font-bold text-gray-500 dark:text-gray-400 uppercase tracking-widest border-b border-gray-100/80 dark:border-gray-700/80 bg-gradient-to-r from-gray-50 to-white dark:from-gray-900 dark:to-gray-800 flex items-center gap-2">
            <Globe size={14} className="text-[#00d4ff]" />
            Select Language
          </div>
          {languages.map((lang, index) => (
            <button
              key={lang.code}
              onClick={() => switchLanguage(lang.code)}
              className={`w-full px-4 py-3 text-left transition-all duration-200 flex items-center justify-between group relative overflow-hidden ${
                language === lang.code 
                  ? 'bg-gradient-to-r from-blue-500/10 via-cyan-500/10 to-blue-500/10 text-blue-600 dark:text-cyan-400' 
                  : 'text-gray-700 dark:text-gray-300 hover:bg-gradient-to-r hover:from-blue-50/50 hover:via-cyan-50/50 hover:to-blue-50/50 dark:hover:from-blue-900/20 dark:hover:via-cyan-900/20 dark:hover:to-blue-900/20'
              } ${index !== languages.length - 1 ? 'border-b border-gray-100/50 dark:border-gray-700/50' : ''}`}
            >
              {/* Hover effect background */}
              <div className={`absolute inset-0 bg-gradient-to-r from-blue-400/0 via-cyan-400/5 to-blue-400/0 dark:via-cyan-400/10 translate-x-[-100%] group-hover:translate-x-[100%] transition-transform duration-700 ease-out`}></div>
              
              <div className="flex items-center gap-3 relative z-10">
                <div className={`transition-transform duration-200 ${language === lang.code ? 'scale-110' : 'group-hover:scale-105'}`}>
                  <lang.FlagComponent className="w-8 h-5 rounded shadow-sm" />
                </div>
                <div className="flex flex-col">
                  <span className={`font-semibold text-sm ${language === lang.code ? 'text-blue-600 dark:text-cyan-400' : 'text-gray-900 dark:text-gray-100 group-hover:text-gray-700 dark:group-hover:text-gray-200'}`}>
                    {lang.nativeName}
                  </span>
                  <span className={`text-xs ${language === lang.code ? 'text-blue-500/70 dark:text-cyan-500/70' : 'text-gray-500 dark:text-gray-400'}`}>
                    {lang.name}
                  </span>
                </div>
              </div>
              {language === lang.code && (
                <div className="relative z-10 flex items-center gap-1">
                  <div className="w-1.5 h-1.5 bg-blue-500 dark:bg-cyan-400 rounded-full animate-pulse"></div>
                  <Check size={18} className="text-blue-600 dark:text-cyan-400 animate-[bounce_1s_ease-in-out]" strokeWidth={3} />
                </div>
              )}
            </button>
          ))}
          
          {/* Bottom decoration */}
          <div className="h-1 bg-gradient-to-r from-blue-400 via-cyan-400 to-blue-400 opacity-50 dark:opacity-70"></div>
        </div>
      )}
    </div>
  );
};

export default LanguageSwitcher;
